<template>
  <el-container class="chat-page-container">
    <el-header class="chat-page-head" height="7%">
      <div>
        <el-dropdown trigger="click" style="margin-top: 7px">
            <span class="el-dropdown-link channel-title">
              <strong>{{chatInfo.chatName}}</strong><i class="el-icon-arrow-down el-icon--right"></i>
            </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="changeChatNameBtn">修改群聊名</el-dropdown-item>
            <el-dropdown-item @click.native="deleteChatBtn">删除群聊</el-dropdown-item>
            <el-dropdown-item @click.native="quitChatBtn" divided>退出群聊</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <el-button round class="online-num-button" @click="onlineDrawer = true" icon="el-icon-user-solid">
          <strong>{{onlineNickName.length}}/{{chatMember.length}}</strong>
        </el-button>
        <el-drawer title="在线列表" :visible.sync="onlineDrawer" size="20%">
          <div class="chat-for-chat-page" v-for="(memberOn,index1) in this.onlineNickName" :key="index1+'1'">
            <el-badge is-dot class="item online-tag"/>
            <div class="online-name-on">{{memberOn}}</div>
          </div>
          <div  v-for="(memberOff,index) in this.chatMember" :key="index+'2'">
            <div class="chat-for-chat-page" v-if="onlineNickName.indexOf(memberOff.nickName) == -1">
              <div class="el-badge item online-tag">
                <sup class="el-badge__content el-badge__content--info is-dot2"></sup>
              </div>
              <div class="online-name-off">{{memberOff.nickName}}</div>
            </div>
          </div>
        </el-drawer>
      </div>
      <el-divider style="margin: 12px"></el-divider>
    </el-header>
    <el-main class="chat-page-main" height="60%" id="showMsg">
      <div class="ppp" id="messageList">
        <div :id="'message_' + item.time" v-for="(item, index) in this.messageList" :key="index">
          <div v-if="item.messageType == 0" :class="item.userInfo.userName == userId ? 'one-message-right' :'one-message'">
            <div :class="item.userInfo.userName == userId ? 'status-wrapper-right' : 'status-wrapper'">
<!--              <div v-if="item.userInfo.avatarUrl" style="width: 32px; height:32px;"><img class="status-wrapper-image" :src="item.userInfo.avatarUrl" /></div>-->
              <template >{{ item.userInfo.firstLetter.toUpperCase() }}</template>
            </div>
            <div :class="item.userInfo.userName == userId ? 'message-content-right' : 'message-content'">
              <div :class="item.userInfo.userName == userId ? 'message-content-nameAndDate-right' : 'message-content-nameAndDate'">
                <span class="message-content-nickName">{{item.userInfo.nickName ? item.userInfo.nickName : item.userInfo.userName}}</span>
                <span v-if="item.userInfo.userName != userId" class="message-content-date">{{getCreateDateTime(item)}}</span><br/>
              </div><br/>
              <span :class="item.userInfo.userName == userId ? 'message-bubble-right' : 'message-bubble-left'">{{item.msg}}</span>
            </div>
          </div>
          <div v-else-if="item.messageType == 1 && item.userInfo.userName != userId"  class="one-message" style="color: #7e7ed2; font-size: 15px">
            <div class="online-message" style="border-radius: 30px">
              <span>{{item.userInfo.nickName}} </span>
              <span>{{item.msg}}</span>
            </div>
          </div>
          <div v-else-if="item.messageType == 2" class="one-message" style="color: #c1c0c0; font-size: 15px">
            <div class="online-message" style="border-radius: 30px">
              <span>{{item.userInfo.nickName}} </span>
              <span>{{item.msg}}</span>
            </div>
          </div>
          <div v-else-if="item.messageType == 4" class="one-message" style="color: #c2691a; font-size: 15px">
            <div class="online-message" style="border-radius: 30px">
              <span>{{item.userInfo.nickName}} </span>
              <span>{{item.msg}}</span>
            </div>
          </div>
          <div v-else-if="item.messageType == 5" class="one-message" style="color: #c1c0c0; font-size: 15px">
            <div class="online-message" style="border-radius: 30px">
              <span>{{item.userInfo.nickName}} 把群聊名修改为 </span>
              <span>{{item.msg}}</span>
            </div>
          </div>
          <div v-else-if="item.messageType == 999" class="more-recorder" style="color: #c1c0c0; font-size: 15px">
            <span v-on:click="getMoreHistory()" class="load-more">点击加载更多消息</span>
          </div>
        </div>
      </div>
    </el-main>
    <el-footer class="chat-page-foot" height="30%">
<!--      <el-divider style="margin-top: 10px"></el-divider>-->
      <div class="foot-hr"/>
      <div>
        <div>
          <div class="chat-page-tool-box">
            <el-popover
                class="emoji-popover"
                placement="top"
                v-model="visible">
              <div class="browBox">
                <ul class="emoji-ul">
                  <li class="emoji-li" v-for="(item,index) in faceList" :key="index" @click="getBrow(index)">{{item}}</li>
                </ul>
              </div>
              <el-button  round size="small" slot="reference">😀</el-button>
            </el-popover>
          </div>
          <el-input class="send-msg-input"
                    :rows="4"
                    type="textarea"
                    placeholder="请输入内容"
                    @keydown.enter.native="send()"
                    v-model="textContent">
          </el-input>

          <el-button type="primary" size="small" class="send-msg-send-btn" @click="send">发送</el-button>
          <div v-html="deleteConfirm">
            <div v-if="$route.params.chatId == chatId"></div>
          </div>
        </div>
      </div>
    </el-footer>
  </el-container>
</template>

<script>
import {getChatById, getChatMemberById, getMsgRecorder, deleteChat, quitChat, changeChatName} from "@/api/channel";
import Global from "@/utils/Global";
const appData = require("@/assets/emojis.json");

export default {
  name: "ChatPage",
  props: ['chatIdToUpdate'],
  data() {
    return {
      deleteFlag: false,
      deleteMsg: null,
      deleteConfirm: null,
      isLoadMore: false,
      times: 0,
      userId: null,
      ws: null,
      visible: false,
      chatId: null,
      textContent: "",
      faceList: [],
      getBrowString: "",
      content: [],
      onlineDrawer: false,
      messageList: [],
      chatInfo: {
        chatName: null,
      },
      chatMember: [],
      onlineNickName: [],
      wsAddress: Global.WebSocketServerAddress,
    };
  },
  methods:{
    initPage(){
      let _this = this;
      const chatId = this.$route.params.chatId
      _this.chatId = chatId
      getChatById(chatId)
          .then(response => {
            this.chatInfo = response.data.data
          })
      getChatMemberById(chatId)
          .then(response => {
            this.chatMember = response.data.data
          })
      getMsgRecorder(chatId, 0)
          .then(response => {
            let data = response.data.data
            for(let i in data){
              let message = {
                time: data[i].time,
                msg: data[i].message,
                messageType: 0,
                userInfo: {
                  nickName: data[i].userNickNameFrom,
                  firstLetter: data[i].firstLetter,
                  avatarUrl: data[i].headUrl,
                  userName: data[i].userNameFrom,
                }
              }
              _this.messageList.unshift(message)
            }
            _this.$nextTick(() => {
              var container = document.getElementById('showMsg');
              container.scrollTop = container.scrollHeight;
            });
            let obj={
              messageType:999
            }
            _this.messageList.unshift(obj)
            _this.times = this.times+data.length
          })
      if(!window.WebSocket){
        console.log('浏览器不支持websocket');
      }else {
        let serverHost = this.wsAddress;
        let groupId = this.$route.params.chatId;
        let userId = JSON.parse(sessionStorage.getItem('currentUser')).userName
        this.userId = userId
        let url = 'wss://'+serverHost+':8081/groupChat/' + groupId + '/' + userId;
        let ws = new WebSocket(url);
        this.ws = ws;
        ws.onopen = function (){
          console.log("客户端连接成功")
        }
        ws.onerror = function (){
          console.log("websocket连接异常")
        }
        ws.onmessage = function (e){
          let data = JSON.parse(e.data)
          if(data.messageType == 0){//普通消息
            _this.times++
            _this.$emit("getNewMsg",chatId)
          }
          if(data.messageType == 1 || data.messageType == 2){//上线，离线通知
            // _this.onlineMember = data.onlineMember
            _this.onlineNickName = data.onlineMember
          }
          if(data.messageType == 3){//频道删除
            _this.$emit("getNewMsg",chatId)
            _this.deleteMsg = data.userInfo.nickName+data.msg
            _this.deleteFlag = true
          }
          if(data.messageType == 4){//退出频道
            let chatMember = _this.chatMember
            for(let i in chatMember){
              if (chatMember[i].userName == data.userInfo.userName){
                _this.chatMember.splice(i,1)
              }
            }
            _this.onlineNickName = data.onlineMember
          }
          if(data.messageType == 5){//修改群聊名
            let newName = data.msg
            _this.chatInfo.chatName = newName
          }
          if(data.messageType == 8){//有成员修改信息
            console.log("生效了")
            let userInfo = data.message
            let messageList = _this.messageList
            for(let i in messageList){
              if (messageList[i].messageType == 0){
                if(messageList[i].userInfo.userName == userInfo.userName){
                  if(userInfo.nickName != null){
                    _this.messageList[i].userInfo.nickName = userInfo.nickName
                  }
                  if(userInfo.avatarUrl != null){
                    _this.messageList[i].userInfo.avatarUrl = userInfo.avatarUrl
                  }
                  if(userInfo.firstLetter != null){
                    _this.messageList[i].userInfo.firstLetter = userInfo.firstLetter
                  }
                }
              }
            }
          }
          _this.messageList.push(data)
          _this.$nextTick(() => {
            var container = document.getElementById('showMsg');
            container.scrollTop  = container.scrollHeight;
          });
          this.chatIdToUpdate = chatId

        }
      }
    },
    changeChatNameBtn(){
      let _this = this
      this.$prompt('请输入新的群聊名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: this.chatInfo.chatName,
        inputErrorMessage: '名称格式不正确'
      }).then(({ value }) => {
        changeChatName(this.chatId, this.userId, value)
            .then(response => {
              let data = response.data
              if(data.code == 200){
                this.$notify({
                  title: '成功',
                  message: data.data,
                  duration: 2500,
                  type: 'success'
                });
                _this.$emit("chatNameChanged", this.chatId, value)
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消修改'
        });
      });
    },
    quitChatBtn(){
      let _this = this
      this.$confirm('是否要退出该群聊?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        quitChat(this.chatId, this.userId)
            .then(response => {
              let data = response.data
              if(data.code == 200){
                this.$notify({
                  title: '成功',
                  message: data.data,
                  duration: 2500,
                  type: 'success'
                });
                this.ws.close()
                _this.$emit("deleteChatId", this.chatId)
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退出'
        });
      });
    },
    deleteChatBtn(){
      this.$confirm('此操作将删除改群聊, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteChat(this.chatId, this.userId)
            .then(response => {
              let data = response.data
              if(data.code == 200){
                this.$notify({
                  title: '成功',
                  message: data.data,
                  duration: 2500,
                  type: 'success'
                });
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    deleteChatInfo(msg){
      let _this = this
      this.$alert(msg, '该群聊即将关闭', {
        confirmButtonText: '收到',
        callback: action => {
          this.ws.close()
          console.log(action)
          _this.$emit("deleteChatId", this.chatId)
        }
      });
    },
    // 获取用户点击之后的标签 ，存放到输入框内
    getBrow(index) {
      for (let i in this.faceList) {
        if (index == i) {
          this.getBrowString = this.faceList[index];
          this.textContent += this.getBrowString;
        }
      }
    },
    send(){
      let _this = this;
      if (this.textContent.trim() == '' || this.textContent.trim() == null){
        const h = this.$createElement;
        this.$message({
          message: h('p', null, [
            h('span', null, '消息为空'),
          ])
        })
      }else {
        _this.ws.send(this.textContent);
        _this.textContent = ''
      }
      let e = window.event;
      e.returnValue = false;
      return false;
    },
    getCreateDateTime(message) {
      return new Date(message.time).toLocaleString()
    },
    getMoreHistory(){
      this.isLoadMore = true
      let _this = this
      _this.messageList.splice(0,1)
      getMsgRecorder(this.chatId, this.times)
          .then(response => {
            let data = response.data.data
            for(let i in data){
              let message = {
                time: data[i].time,
                msg: data[i].message,
                messageType: 0,
                userInfo: {
                  nickName: data[i].userNickNameFrom,
                  firstLetter: data[i].firstLetter,
                  avatarUrl: data[i].headUrl,
                  userName: data[i].userNameFrom
                }
              }
              _this.messageList.unshift(message)
            }
            if(data.length == 10){
              let obj={
                messageType:999
              }
              _this.messageList.unshift(obj)
            }else if(data.length < 1){
              this.$message('没有更多消息了');
            }
            _this.times = this.times+data.length
          })
    }
  },
  mounted: function (){
    for (let i in appData) {
      this.faceList.push(appData[i].char);
    }
    this.initPage()
  },
  watch: {
    '$route'(){
      if(this.deleteFlag == true && this.$route.params.chatId == this.chatId){
        this.deleteChatInfo(this.deleteMsg)
      }
    },
    deleteFlag(val){
      if(val == true && this.$route.params.chatId == this.chatId){
        this.deleteChatInfo(this.deleteMsg)
      }
    }
  },

}
</script>

<style >
.ppp{
  position: relative;
}
.chat-page-container{
  height: 100%;
  width: 100%;
}
.chat-page-head{
  height: 6%;
  width: 100%;
  /*background-color: #f6f8f8;*/
  border-radius: 4px;
  border: 1px;
  padding: 5px;
  margin-bottom: 11px;
}

.chat-page-main{
  height: 50%;
  width: 100%;
}
.chat-page-main::-webkit-scrollbar {
  width: 4px;
  /*height: 4px;*/
}
.chat-page-main::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 5px rgba(61, 47, 47, 0.2);
  background: rgb(90, 90, 90);
}
.chat-page-main::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
  border-radius: 0;
  background: rgba(144, 97, 97, 0.1);
}
.chat-page-foot{
  height: 30%;
  width: 100%;
  /*background-color: azure;*/
}
.channel-title:hover{
  color: #409EFF;
}
.el-dropdown-link {
  font-size: 20px;
  cursor: pointer;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.online-num-button{
  float: right;
}
.el-dropdown{
  vertical-align: middle;
}
.emoji-popover{
  margin-right: 10px;
  margin-bottom: 10px;
  float: left;
}
.emoji-ul{
  display: flex;
  flex-wrap: wrap;
  padding: 10px;
}
.emoji-li{
  list-style: none;
  padding: 1px 1px;
  width: 10%;
  font-size: 26px;
  list-style: none;
  text-align: center;
}
.browBox{
  width: 97%;
  height: 100%;
  position: absolute;
  bottom: 10px;
}
.send-msg-input{
  margin-bottom: 10px;
  height: 108px;
  min-height: 108px;
}
.send-msg-send-btn{
  float: right;
}
.tool-box-icon{
  float: left;
}

.status-wrapper {
  width: 32px;
  height: 32px;
  line-height: 32px;
  background-color: #DF016E;
  border-radius: 32px;
  text-align: center;
  color: #fff;
  font-weight: bold;
  float: left;
  margin-right: 6px;
}
.status-wrapper-right {
  width: 32px;
  height: 32px;
  line-height: 32px;
  background-color: #DF016E;
  border-radius: 32px;
  text-align: center;
  color: #fff;
  font-weight: bold;
  float: right;
  margin-right: 6px;
}
.status-wrapper-image {
  border-radius: 100%;
  width: 100%;
  height: 100%;
  background-color: #BCB2A6;
}
.message-content{
  float: left;
}
.message-content-right{
  float: right;
}
.message-content-date {
  font-size: 12px;
  color: #8F8B86;
  padding: 0 0 0 10px;
  margin-top: -2px;
}
.message-content-nickName {
  text-overflow: ellipsis;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
  display: inline-block;
}
.message-bubble-left {
  float:left;
  width: auto;
  max-width: 300px;
  height: auto;
  margin: 7px;
  background-color: #979693;
  border-bottom-color: #050709;
  /*为了给after伪元素自动继承*/
  color: #fff;
  font-size: 20px;
  line-height: 25px;
  padding: 9px 12px 9px 12px;
  box-sizing: border-box;
  border-radius: 6px;
  position: relative;
  word-break: break-all;
}
.message-bubble-left::before {
  content: '';
  position: absolute;
  top: 20px;
  left: -3px;
  width: 8px;
  height: 8px;
  margin-top: -10px;
  background: inherit;
  /*自动继承父元素的背景*/
  transform: rotate(45deg);
}
.message-bubble-right {
  float:left;
  width: auto;
  max-width: 300px;
  height: auto;
  margin: 7px;
  background-color: #007ACC;
  border-bottom-color: #050709;
  /*为了给after伪元素自动继承*/
  color: #fff;
  font-size: 20px;
  line-height: 25px;
  padding: 9px 12px 9px 12px;
  box-sizing: border-box;
  border-radius: 6px;
  position: relative;
  word-break: break-all;
}
.message-bubble-right::before {
  content: '';
  position: absolute;
  top: 20px;
  right: -3px;
  width: 8px;
  height: 8px;
  margin-top: -10px;
  background: inherit;
  /*自动继承父元素的背景*/
  transform: rotate(45deg);
}
.one-message{
  float: left;
  width: 100%;
}
.online-message{
  padding: 0px 80px 0px 0px;
}
.one-message-right{
  float: right;
  width: 100%;
}
.message-content-nameAndDate{
  float: left;
  margin-left: 10px;
}
.message-content-nameAndDate-right{
  float: right;
  margin-right: 13px;
}
.el-container{
  padding: 0px;
  margin: 0px;
  height: 100vh;
}
.foot-hr{
  height: 1px;
  display: block;
  margin-bottom: 5px;;
  width: 100%;
  background-color: #DCDFE6;
  position: relative;
  color: #333;
  text-align: center;
  font-family: Avenir, Helvetica, Arial, sans-serif;
}
.online-name-on{
  font-weight: bold;
  color: #2f2f2f;
  float: left;
  margin-left: 10px;
}
.online-name-off{
  font-weight: lighter;
  color: #8c939d;
  float: left;
  margin-left: 10px;
}
.load-more{
  margin-right: 8%;
}
.load-more:hover{
  color: #3a8ee6;
  cursor: pointer ;
  margin-right: 8%;
}
.red-tag{
  background-color: red;
  float: left;
  width: 19px;
  border-radius: 60%;
  text-align: center;
}
.chat-for-chat-page{
  height: 33px;
  overflow: hidden;
}
.online-tag{
  float: left;
  margin-left: 50px;
  margin-top: 5px;
}
.el-badge__content.is-dot{
  background-color: #5ede20;
}
.el-badge__content.is-dot2 {
  background-color: #8F8B86;
  height: 8px;
  width: 8px;
  padding: 0;
  right: 0;
  border-radius: 50%;
}

</style>
